using System;
using System.Reflection;

namespace Coderoom.ScrumPlanner.Tests.Unit.Internal
{
	// Source: http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributes.aspx (David M. Kean - MSFT)
	internal static class AttributeTestHelper
	{
		internal static TAttribute[] GetCustomPropertyAttributes<TType, TAttribute>(string propertyName) where TAttribute : Attribute
		{
			var property = typeof (TType).GetProperty(propertyName);

			if (property == null)
				return null;

			return GetCustomAttributes<TAttribute>(property, true);
		}

		internal static T[] GetCustomAttributes<T>(this ICustomAttributeProvider provider) where T : Attribute
		{
			return GetCustomAttributes<T>(provider, true);
		}

		internal static T[] GetCustomAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute
		{
			if (provider == null)
				throw new ArgumentNullException("provider");

			var attributes = provider.GetCustomAttributes(typeof (T), inherit) as T[];
			if (attributes == null)
			{
				// WORKAROUND: Due to a _bug in the code for retrieving attributes
				// from a dynamic generated parameter, GetCustomAttributes can return
				// an instance of an object[] instead of T[], and hence the cast above
				// will return null.
				return new T[0];
			}

			return attributes;
		}
	}
}